import React, { useState } from 'react'
import { api2 } from '../api';
import { useHistory, NavLink } from "react-router-dom";

import './sign-in9.css'

const Register9 = (props) => {
  props = {
    rootClassName: '',
    heading1: 'Регистрация',
    action1: 'Зарегистрироваться',
    action2: 'Войти в аккаунт',
    content1: "Уже есть аккаунт?",
    ...props
  }

  const history = useHistory();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState(false);
  const [errorText, setErrorText] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      setError(true);
      setErrorText('Пароли не совпадают');
      return;
    }
    try {
      const response = await api2.send('userRegister', { email, password });
      if (response.success) {
        setError(false);
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('user', JSON.stringify(response.data.user));
        window._LC_._user = response.data.user;
        history.push('/home');
      } else {
        setErrorText('Ошибка при регистрации: ' + response.error)
        setError(true)
        console.error('Registration failed:', response.error);
      }
    } catch (error) {
      setError(true)
      setErrorText('Ошибка сети, попробуйте еще раз')
      console.error('Error registering:', error);
    }
  };

  return (
      <div
          className={`register9-container thq-section-padding ${props.rootClassName} `}
      >
        <div className="register9-max-width thq-section-max-width">
          <div className="register9-container1">
            <h2 className="register9-text thq-heading-2">{props.heading1}</h2>
          </div>
          <div className="register9-container2">
            <div className="register9-container3">
              <form onSubmit={handleSubmit} className="register9-form">
                <div className="register9-email">
                  <label htmlFor="thq-register-9-email" className="thq-body-large">
                    Электронная почта
                  </label>
                  <input
                      type="email"
                      id="thq-register-9-email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required={true}
                      placeholder="Ваша почта"
                      className="register9-textinput thq-body-large thq-input"
                  />
                </div>
                <div className="register9-password">
                  <div className="register9-container4">
                    <label
                        htmlFor="thq-register-9-password"
                        className="thq-body-large"
                    >
                      Пароль
                    </label>
                  </div>
                  <input
                      type="password"
                      id="thq-register-9-password"
                      required={true}
                      placeholder="Ваш пароль"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="register9-textinput1 thq-body-large thq-input"
                  />
                </div>
                <div className="register9-confirm-password">
                  <div className="register9-container4">
                    <label
                        htmlFor="thq-register-9-confirm-password"
                        className="thq-body-large"
                    >
                      Подтвердите пароль
                    </label>
                  </div>
                  <input
                      type="password"
                      id="thq-register-9-confirm-password"
                      required={true}
                      placeholder="Подтвердите пароль"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      className="register9-textinput1 thq-body-large thq-input"
                  />
                </div>
                <button
                    type="submit"
                    className="register9-button thq-button-filled"
                >
                <span className="register9-text3 thq-body-small">
                  {props.action1}
                </span>
                </button>
              </form>
              {error && <p className="register9-text5 thq-body-large">{errorText}</p>}
            </div>
            <div className="register9-divider">
              <div className="register9-container5">
                <div className="register9-divider1"></div>
                <span className="thq-body-large">Или</span>
                <div className="register9-divider2"></div>
              </div>
              <p className="register9-text5 thq-body-large">{props.content1}</p>
            </div>
            <div className="register9-container6">
              <div className="register9-container7">
                <NavLink to="/login" className="register9-button1 thq-button-outline">
                  <span className="thq-body-small">{props.action2}</span>
                </NavLink>
              </div>
            </div>
          </div>
        </div>
      </div>
  )
}

export default Register9